package api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import appmodel.AppCommentResponse;
import appmodel.JsonModel;
import common.StringUtil;
import model.Comment;
import model.CommentLabel;
import model.Order;
import model.User;
import net.sf.json.JSONObject;
import service.CommentLabelService;
import service.CommentService;
import service.IncomeService;
import service.OrderService;
import service.UserService;

@Controller
@RequestMapping({ "/comment" })
public class CommentController {

	@Autowired
	private CommentService commentService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private IncomeService incomeService;
	
	/**
	 * 根据订单获取评论
	 */
	@RequestMapping(value = { "/getByOrderId" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject getCommentByOrderId(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "userId", required = false) Long userId) {

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		List<Comment> list = this.commentService.getCommentByOrderId(orderId);

		AppCommentResponse appcommentResponse = new AppCommentResponse();
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Comment comment = list.get(i);
				if (!StringUtil.isEmpty(comment.getCommentCreateUserid()) && comment.getCommentCreateUserid() != 0) {
					User user = userService.getUserInfo(comment.getCommentCreateUserid());
					if (null != user) {
						comment.setUserName(user.getUserName());
					}
					appcommentResponse.setCommentCreateOrderInfo(comment);
				} else if (!StringUtil.isEmpty(comment.getCommentedUserid()) && comment.getCommentedUserid() != 0) {
					User user = userService.getUserInfo(comment.getCommentedUserid());
					if (null != user) {
						comment.setUserName(user.getUserName());
					}
					appcommentResponse.setCommentGetOrderInfo(comment);
				}
			}
		}
		
		if(null == appcommentResponse.getCommentCreateOrderInfo()){
			appcommentResponse.setCommentCreateOrderInfo(new Comment());
		}
		
		if(null == appcommentResponse.getCommentGetOrderInfo()){
			appcommentResponse.setCommentGetOrderInfo(new Comment());
		}

		if (null != list) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("查询成功");
			jsonModel.setjData(appcommentResponse);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("查询失败");
			jsonModel.setjData(appcommentResponse);
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

	
	@Autowired
	private CommentLabelService commentLabelService;
	
	/**
	 * 添加评论的接口
	 */
	@RequestMapping(value = { "/engineer/add" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject insert(HttpServletRequest request, JsonModel jsonModel,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "commentContent", required = false) String commentContent,
			@RequestParam(value = "score", required = false) int score,
			@RequestParam(value = "label_id", required = false) String label_id,
			@RequestParam(value = "label_name", required = false) String label_name,
			@RequestParam(value = "userId", required = false) Long userId) {
		
		Order order = orderService.getOrderDetail(orderId);
		
//		1、未抢单(快速抢修)   2、未抢单(预约维修)        3、已抢单（待处理）4、（处理中）5、待评价 （维修成功）  6、已完成（维修成功） 
//		7、已取消 8、已完成（维修失败） 9待评价（维修失败） 10、全部  11、待评价（包括成功和失败） 12、已完成（包括成功和失败）
		
		if(null == order) {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("获取订单失败");
			jsonModel.setjData("");
			jsonModel.setToken("");
		}else {
			if(order.getState() == 5 || order.getState() == 9) {
				int orderState = 0;
				if(order.getState() == 5) {//维修成功
					orderState = 6;
				}else if(order.getState() == 9) {//维修失败
					orderState = 8;
				}
				
				//修改订单的状态 
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("orderId", orderId);
				map.put("state", "" + orderState);
				map.put("order_get_user_id", userId);
				
				this.orderService.modifyOrderState(map);
				
				//修改余额
				Map<String,Object> mapIncome = new HashMap<>();
				double moneyAll = (order.getPrice() + order.getAdditionalPrice());
				mapIncome.put("income_number", moneyAll);
				mapIncome.put("userId", userId);
				mapIncome.put("createDate", new Date());
				Integer result = incomeService.withDraw(map);
				
				//添加评论的内容
				Comment comment = new Comment();
				comment.setCommentCreatDate(new Date());
				comment.setCommentedUserid(userId);
				comment.setLabelId(label_id);
				comment.setComment_content(commentContent);
				comment.setScore(score);
				comment.setCommentOrderId(orderId);
				comment.setLabel_name(label_name);

				int addOrder = commentService.addComment(comment);

				String[] labelId = label_id.split(",");
				String[] labelName = label_name.split(",");
				for (int i = 0; i < labelId.length; i++) {
					CommentLabel commentLabel = new CommentLabel();
					commentLabel.setOrderName(orderId);
					commentLabel.setUserId(userId);
					int int_labelId = Integer.parseInt(labelId[i]);
					commentLabel.setLabelId(int_labelId);
					commentLabel.setLabelName(labelName[i]);
					
					commentLabelService.addCommentLabel(commentLabel);
				}
				
				if (addOrder > 0) {
					jsonModel.setSuccess(true);
					jsonModel.setMsg("评论成功");
					jsonModel.setjData("");
					jsonModel.setToken("");
				} else {
					jsonModel.setSuccess(false);
					jsonModel.setMsg("评论失败");
					jsonModel.setjData("");
					jsonModel.setToken("");
				}
			}else {
				jsonModel.setSuccess(false);
				jsonModel.setMsg("该订单此状态不可评论");
				jsonModel.setjData("");
				jsonModel.setToken("");
			}
		}
		return JSONObject.fromObject(jsonModel);
	}

	@Autowired
	private OrderService orderService;

	/**
	 * 添加评论的接口
	 */
	@RequestMapping(value = { "/user/add" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject insertUserComment(HttpServletRequest request, JsonModel jsonModel, HttpServletResponse response,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "commentContent", required = false) String commentContent,
			@RequestParam(value = "score", required = false) int score,
			@RequestParam(value = "label_id", required = false) String label_id,
			@RequestParam(value = "label_name", required = false) String label_name,
			@RequestParam(value = "repairResult", required = false) int repairResult,
			@RequestParam(value = "userId", required = false) Long userId) {// 1为成功， 2为失败

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min

		Comment comment = new Comment();
		comment.setCommentCreatDate(new Date());
		comment.setCommentedUserid(userId);
		comment.setLabelId(label_id);
		comment.setComment_content(commentContent);
		comment.setScore(score);
		comment.setCommentOrderId(orderId);
		comment.setLabel_name(label_name);
		int addOrder = commentService.addComment(comment);
		
		String[] labelId = label_id.split(",");
		String[] labelName = label_name.split(",");
		for (int i = 0; i < labelId.length; i++) {
			CommentLabel commentLabel = new CommentLabel();
			commentLabel.setOrderName(orderId);
			commentLabel.setUserId(userId);
			commentLabel.setLabelId(Integer.parseInt(labelId[i]));
			commentLabel.setLabelName(labelName[i]);
			
			commentLabelService.addCommentLabel(commentLabel);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderId", orderId);
		int orderState = 0;
		if (repairResult == 1) {// 待评价(维修成功)
			orderState = 5;
		} else if (repairResult == 2) {// 待评价(维修失败)
			orderState = 9;
		}
		map.put("state", "" + orderState);
		this.orderService.modifyOrderState(map);

		if (addOrder > 0) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("评论成功");
			jsonModel.setjData("");
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("评论失败");
			jsonModel.setjData("");
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}

}